package com.macaline.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.macaline.bean.JsapiTicket;
import com.xnx3.DateUtil;
import com.xnx3.net.HttpsUtil;
import com.xnx3.weixin.WeiXinUtil;
import com.xnx3.weixin.bean.AccessToken;

import net.sf.json.JSONObject;

/**
 * 微信相关
 * @author warm_joy
 *<p>Description:  </p>
 *<p>date: 2019-04-16 10:42}</p>
 *<p>company: ww.leimingyun.com </p>
 */
@SuppressWarnings("deprecation")
public class WXUtil {
	private static WeiXinUtil weiXinUtil; // 微信工具类
	public static JsapiTicket jsapiTicket; // 二维码相关参数
	private final static String TICKET_URL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";
	
	/**
	 * 获取微信工具类
	 * @author warm_joy
	 * @return
	 */
	public static WeiXinUtil getWXUtil() {
		if(weiXinUtil == null) {
//			weiXinUtil = new WeiXinUtil(Global.get("WEIXIN_APPID"),Global.get("WEIXIN_APPSECRET"),Global.get("WEIXIN_TOKEN"));
		}
		return weiXinUtil;
	}
	
	/**
	 * 生成一个直接二维码
	 * @author warm_joy
	 * @param text 二维码内信息
	 * @return 成功返回二维码url，否则返回null
	 */
	public static String createTicket(String text) {
		String ticketParam = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"" +  text + "\"}}}";
		String ticketString = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";
		String access_token = getWXUtil().getAccessToken().getAccess_token();
		String url = ticketString + access_token;
		@SuppressWarnings({ "resource"})
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		JSONObject jsonObject = null;
		try {
			StringEntity stringEntity = new StringEntity(ticketParam,"UTF-8");
			
			stringEntity.setContentEncoding("UTF-8");
			stringEntity.setContentType("application/json");
			post.setEntity(stringEntity);
			post.setHeader("Content-Type", "application/json; charset=UTF-8");
			post.setHeader("Charset", "UTF-8");
			HttpResponse response = client.execute(post);
			if(response.getStatusLine().getStatusCode() ==HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				String result = EntityUtils.toString(entity);
				jsonObject = JSONObject.fromObject(result); 
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		String ticket = jsonObject.getString("ticket");
		if(ticket == null) {
			return null;
		}
		return TICKET_URL + ticket;
	}
	/**
	 * 得到自定义分享朋友圈的ticket参数
	 * @author warm_joy 
	 * @return 获取成功返回ticket,否侧返回null
	 */
	public static String getTicket() {
		//获取ticket的url
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
		//判断是否在缓存时间内，如果超出重新获取，
		if(jsapiTicket == null || DateUtil.timeForUnix10() > jsapiTicket.getGainTime() + JsapiTicket.CACHE_TIME) {
			jsapiTicket = new JsapiTicket();
			//通过微信工具得到access——token
			AccessToken accessToken = WXUtil.getWXUtil().getAccessToken();
			String access_token = accessToken.getAccess_token();
			System.out.println("access_token :"  + access_token);
			//判断access有没有设置获取时间
			//如果没有设置当前时间为获取时间
			if(!(accessToken.getGainTime() > 100) || 
					DateUtil.timeForUnix10() > accessToken.getGainTime() + 5000) {
				accessToken.setGainTime(DateUtil.timeForUnix10());
				System.out.println("时间：" + accessToken.getGainTime());
			}
			//创建获取tick的url
			url = url.replace("ACCESS_TOKEN", access_token);
			//发送get请求
			HttpsUtil httpsUtil = new HttpsUtil();
			com.xnx3.net.HttpResponse httpResponse = httpsUtil.get(url);
			JSONObject response = JSONObject.fromObject(httpResponse.getContent());
			//判断get请求是否获取成功
			if(response.getString("errcode").equals("0") && response.getString("ticket") != null) {
				//进行ticket的缓存
				jsapiTicket.setTicket(response.getString("ticket"));
				jsapiTicket.setGainTime(DateUtil.timeForUnix10());
				return response.getString("ticket");
			}else {
				return null;
			}
		}else {
			//如果ticket已经获得并且在缓存时间内，直接返回已缓存的ticket
			return jsapiTicket.getTicket();
		}
		
	}
	
}
